import { CloseCircleOutlined } from "@ant-design/icons";
import Card from "@/components/Card";
import { FC, PropsWithChildren, useEffect, useState } from "react";
import {
  Col,
  Row,
  Checkbox,
  Modal,
  Avatar,
  Tooltip,
  Button,
  message
} from "antd";
import TopSearch from "@/components/TopSearch";
import { getFriendList, getFriendlist } from "@/api/xhr/friends";
import { SendMessage } from "@/api/xhr/message";
import { addUsersToGroup } from "@/api/xhr/group";
import { useSelector } from "react-redux";

type TypeAddUserToGroupComponent = {
  show: boolean;
  setshow: (data: boolean) => void;
  groupId: number;
  currentGroupUsers: {
    id: number;
    name: string;
    avatar: string;
  }[];
};

type TypeFriendsList = {
  id: number;
  name: string;
  avatar: string;
  checked: boolean;
  inGroup: boolean; // 标记用户是否已在群中
};

const AddUserToGroupComponent: FC<PropsWithChildren<TypeAddUserToGroupComponent>> = ({
  show,
  setshow,
  groupId,
  currentGroupUsers
}) => {
  const userinfo = useSelector((state: any) => state.user.userinfo);
  const [searchVal, setSearchVal] = useState("");
  const [friendslist, setfriendslist] = useState<TypeFriendsList[]>([]);
  const [selectedFriends, setSelectedFriends] = useState<TypeFriendsList[]>([]);

  // 添加用户到群
  async function handleAddToGroup() {
    if (selectedFriends.length === 0) {
      message.error("请至少选择一个好友添加到群");
      return;
    }

    try {
      // 调用后端API添加用户到群
      const res = await addUsersToGroup({
        groupId,
        userList: selectedFriends.map(friend => friend.id),
        userId: userinfo.id
      });
      
      if (res.statusCode === 200) {
        // 发送系统消息通知群成员
        for (const friend of selectedFriends) {
          await SendMessage({
            id: groupId,
            userId: userinfo.id,
            content: `${friend.name} 加入了群聊`,
            type: "group",
            messageType: "system",
            messageSendType: 0
          });
        }

        message.success("成功添加用户到群聊!");
        setshow(false);
      } else {
        message.error(res.errorInfo || "添加用户失败");
      }
    } catch (error) {
      console.error("添加用户到群聊出错:", error);
      message.error("添加用户失败，请稍后重试");
    }
  }

  const handleCancel = () => {
    setshow(false);
  };

  // 选择/取消选择好友
  const onChange = (item: TypeFriendsList, e) => {
    if (item.inGroup) {
      return; // 如果用户已在群中，不允许操作
    }

    if (e.target.checked) {
      setfriendslist(
        friendslist.map(data => {
          if (data.id === item.id) {
            return {
              ...data,
              checked: true
            };
          }
          return data;
        })
      );
      setSelectedFriends([...selectedFriends, { ...item, checked: true }]);
    } else {
      deleteFriend(item.id);
    }
  };

  // 获取好友列表
  useEffect(() => {
    (async function () {
      await loadFriendList();
    })();
  }, []);

  // 从已选列表中删除好友
  function deleteFriend(id: number) {
    setSelectedFriends(selectedFriends.filter(item => item.id !== id));
    setfriendslist(
      friendslist.map(data => {
        if (data.id === id) {
          return {
            ...data,
            checked: false
          };
        }
        return data;
      })
    );
  }

  // 加载好友列表
  async function loadFriendList() {
    try {
      const friendslistres = await getFriendList({ userId: userinfo.id });
      
      // 标记哪些好友已在群中
      const friends = friendslistres.data.map(item => {
        const isInGroup = currentGroupUsers.some(user => user.id === item.id);
        return {
          id: item.id,
          name: item.commendName ? item.commendName : item.userName,
          avatar: item.userAvatar,
          checked: false,
          inGroup: isInGroup
        };
      });
      
      setfriendslist(friends);
    } catch (error) {
      console.error("加载好友列表出错:", error);
      message.error("加载好友列表失败");
    }
  }

  // 搜索好友
  async function searchFunc(searchvalue: string) {
    if (searchvalue) {
      try {
        const res = await getFriendlist({ userId: userinfo.id, searchvalue });
        if (res.statusCode === 200) {
          const friends = res.data.map(item => {
            const isInGroup = currentGroupUsers.some(user => user.id === item.id);
            const isSelected = selectedFriends.some(friend => friend.id === item.id);
            
            return {
              id: item.id,
              name: item.commendName ? item.commendName : item.userName,
              avatar: item.userAvatar,
              checked: isSelected,
              inGroup: isInGroup
            };
          });
          
          setfriendslist(friends);
        }
      } catch (error) {
        console.error("搜索好友出错:", error);
      }
    } else {
      loadFriendList();
    }
  }

  return (
    <Modal
      title="添加成员到群聊"
      open={show}
      onCancel={handleCancel}
      footer={null}
      className="p-1"
      width={600}
      closable={false}
    >
      <Row className="mt-2" gutter={[8, 0]}>
        <Col span={10} className="h-80">
          <div className="flex flex-col h-full w-full">
            <TopSearch
              value={searchVal}
              setvalue={setSearchVal}
              searchFunc={searchFunc}
              className="pt-0"
            ></TopSearch>
            <div className="overflow-y-scroll scrollbar-hide w-full scrollbar select-none cursor-auto flex-1 overflow-x-hidden">
              {friendslist.length ? (
                friendslist.map(item => {
                  return (
                    <Tooltip 
                      key={item.id}
                      title={item.inGroup ? "该用户已在群聊中" : ""}
                    >
                      <div className={item.inGroup ? "opacity-50 cursor-not-allowed" : ""}>
                        <Checkbox
                          onChange={e => onChange(item, e)}
                          checked={item.checked}
                          className="w-full"
                          disabled={item.inGroup}
                        >
                          <Card
                            item={item}
                            className="w-[calc(222px-30px)]"
                            controls={{
                              isshowtime: false,
                              isshowmessage: false,
                              isnav: false
                            }}
                          ></Card>
                        </Checkbox>
                      </div>
                    </Tooltip>
                  );
                })
              ) : (
                <div className="text-sm text-gray-400">暂无数据</div>
              )}
            </div>
          </div>
        </Col>
        <Col span={14} className="flex flex-col">
          <div className="flex flex-col flex-1 relative">
            <div className="flex justify-between">
              <span className="font-medium">添加群成员</span>
              {selectedFriends.length ? (
                <span className="text-gray-500">
                  已选择 {selectedFriends.length} 个联系人
                </span>
              ) : (
                <span className="text-gray-500">未选择联系人</span>
              )}
            </div>
            <div className="px-3 py-2 flex flex-wrap overflow-y-scroll scrollbar-hide w-full scrollbar select-none cursor-auto overflow-x-hidden max-h-[350px]">
              {selectedFriends.length
                ? selectedFriends.map(item => {
                    return (
                      <div
                        className="h-[65px] w-[57px] mt-3 mr-[12px] flex justify-center items-center flex-col"
                        key={item.id}
                      >
                        <div className="relative">
                          <Avatar shape="square" size={48} src={item.avatar} />
                          <CloseCircleOutlined
                            className="absolute top-0 right-0 translate-x-1/2 -translate-y-1/2"
                            onClick={() => deleteFriend(item.id)}
                          />
                        </div>
                        {item.name?.length > 6 ? (
                          <Tooltip
                            title={item.name}
                            color="#87d068"
                            key="#87d068"
                          >
                            <div className="max-w-full truncate whitespace-nowrap overflow-hidden text-center">
                              {item.name}
                            </div>
                          </Tooltip>
                        ) : (
                          <div className="w-12 truncate whitespace-nowrap overflow-hidden text-center">
                            {item.name}
                          </div>
                        )}
                      </div>
                    );
                  })
                : ""}
            </div>
            <div className="p-5 flex justify-center absolute bottom-0 left-14">
              <Button value="small" className="mr-4" onClick={handleCancel}>
                取消
              </Button>
              <Button
                type="primary"
                value="small"
                onClick={handleAddToGroup}
                disabled={selectedFriends.length === 0}
              >
                添加
              </Button>
            </div>
          </div>
        </Col>
      </Row>
    </Modal>
  );
};

export default AddUserToGroupComponent; 